/*
 * $RCSfile: LocalStorage.java,v $
 * $Revision: 1.1 $
 * $Date: 2009-11-02 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.generate.gui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.LinkedHashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>Title: LocalStorage</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class LocalStorage {
    private Map<String, String> properties;
    private static final Logger logger = LoggerFactory.getLogger(LocalStorage.class);

    /**
     * default
     */
    public LocalStorage() {
        this.properties = new LinkedHashMap<String, String>();
    }

    /**
     * @param file
     * @param charset
     * @return LocalStorage
     */
    public static LocalStorage getStorage(File file, String charset) {
        LocalStorage storage = new LocalStorage();

        if(file == null || !file.exists() || !file.isFile()) {
            return storage;
        }

        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(file);
            Map<String, String> map = load(inputStream, charset);
            storage.properties.putAll(map);
        }
        catch(Exception e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                }
            }
        }
        return storage;
    }

    /**
     * @param inputStream
     * @param charset
     * @return LocalStorage
     */
    public static LocalStorage getStorage(InputStream inputStream, String charset) {
        Map<String, String> map = load(inputStream, charset);
        LocalStorage storage = new LocalStorage();
        storage.properties.putAll(map);
        return storage;
    }

    /**
     * @param inputStream
     * @param charset
     * @return Map<String, String>
     */
    private static Map<String, String> load(InputStream inputStream, String charset) {
        if(inputStream != null) {
            try {
                return load(new InputStreamReader(inputStream, charset));
            }
            catch(IOException e) {
                logger.warn(e.getMessage(), e);
            }
        }
        return new LinkedHashMap<String, String>();
    }

    /**
     * @param reader
     * @return Map<String, String>
     */
    private static Map<String, String> load(Reader reader) {
        Map<String, String> map = new LinkedHashMap<String, String>();

        if(reader != null) {
            try {
                String line = null;
                BufferedReader buffer = new BufferedReader(reader);

                while((line = buffer.readLine()) != null) {
                    line = line.trim();

                    if(line.length() < 1) {
                        continue;
                    }

                    if(line.startsWith("#")) {
                        continue;
                    }

                    int i = line.indexOf("=");

                    if(i > -1) {
                        String name = line.substring(0, i).trim();
                        String value = line.substring(i + 1).trim();

                        if(name.length() > 0 && value.length() > 0) {
                            map.put(name, value);
                        }
                    }
                }
            }
            catch(IOException e) {
            }
        }
        return map;
    }

    /**
     * @param file
     * @param text
     * @param charset
     */
    public static void write(File file, String text, String charset) {
        File dir = file.getParentFile();

        if(!dir.exists()) {
            dir.mkdirs();
        }

        OutputStream outputStream = null;

        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(text.getBytes(charset));
            outputStream.flush();
        }
        catch(Exception e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            if(outputStream != null) {
                try {
                    outputStream.close();
                }
                catch (IOException e) {
                }
            }
        }
    }

    /**
     * @param file
     */
    public void save(File file) {
        String content = getContent();
        write(file, content, "utf-8");
    }

    /**
     * @return String
     */
    public String getContent() {
        StringBuilder buffer = new StringBuilder();
        
        for(Map.Entry<String, String> entry : this.properties.entrySet()) {
            buffer.append(entry.getKey());
            buffer.append(" = ");
            
            if(entry.getValue() != null) {
                buffer.append(entry.getValue());
            }
            buffer.append("\r\n");
        }
        return buffer.toString();
    }

    /**
     * @param name
     * @param value
     */
    public void setValue(String name, Object value) {
        if(value != null) {
            this.properties.put(name, value.toString());
        }
        else {
            this.properties.remove(name);
        }
    }

    /**
     * @param name
     * @return String
     */
    public String getValue(String name) {
        return this.properties.get(name);
    }

    /**
     * @param name
     * @param defaultValue
     * @return String
     */
    public String getValue(String name, String defaultValue) {
        String value = this.properties.get(name);

        if(value != null) {
            value = value.trim();
        }

        if(value == null || value.length() < 1) {
            return defaultValue;
        }
        return value;
    }
}
